// 重写数组中的部分方法

// 获取数组的原型
let originArrayProto = Array.prototype;

// 相当于 newArrayProto 继承自 originArrayProto
let newArrayProto = Object.create(originArrayProto);

let methods = [
  // 找到所有的变异方法
  "push",
  "pop",
  "shift",
  "unshift",
  "reverse",
  "sort",
  "splice",
]; // concat slice 都不会改变原数组

methods.forEach((method) => {
  newArrayProto[method] = function (...args) {
    //  内部调用原来的方法，函数劫持(切片编程)
    const result = originArrayProto[method].call(this, ...args);
    // 需要对新的数据再次劫持
    let inserted;
    switch (method) {
      case "push":
      case "unshift":
        inserted = args;
        break;
      case "splice":
        inserted = args.slice(2);
        break;
      default:
        break;
    }
    // console.log("inserted", inserted);
    if (inserted?.length) {
      this.__ob__.observeArray(inserted);
    }
    return result;
  };
});

export { newArrayProto };
